<?php
namespace App\Repository;

use App\Model\UserPay;

use App\Facade\Event;
use App\Event\UserPay\CreateEvent;
use App\Event\UserPay\StatusOkEvent;
use App\Event\UserPay\StatusNoEvent;

class UserPayRepository extends \HyperfStore\Repository
{
    // 放入模型
    public function build()
    {
        return new UserPay;
    }

    // 创建
    public function create(UserRepository $user, $data)
    {
        $this->model->user()->associate($user->model());
        
        $res = $this->save($data);
        
        Event::dispatch(new CreateEvent($this, $user));
        
        return $res;
    }
    
    // 关联上级店铺
    public function setShop(ShopRepository $shop)
    {
        $this->model->shop()->associate($shop->model());
        
        return $this->model->save();
    }
    
    // 支付成功
    public function setStatusOk($code)
    {
        if($this->model->status == UserPay::STATUS_POST)
        {
            $this->model->code   = $code;
            $this->model->status = UserPay::STATUS_OK;
            
            $res = $this->model->save();
            
            Event::dispatch(new StatusOkEvent($this));
            
            return $res;
        }
    }
    
    // 支付关闭
    public function setStatusNo()
    {
        if($this->model->status == UserPay::STATUS_POST)
        {
            $this->model->status = UserPay::STATUS_NO;
            
            $res = $this->model->save();
            
            Event::dispatch(new StatusNoEvent($this));
            
            return $res;
        }
    }
    
    // 是否还可以操作
    public function is()
    {
        return $this->model->status == UserPay::STATUS_POST;
    }
    
    // 需要支付的金额
    public function pay()
    {
        return $this->model->money - $this->model->discount - $this->model->full;
    }
}